﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;

namespace Sissonix.ExtRest.Serialization
{
    /// <summary>
    /// Class for deserializing/serializing to XML.
    /// </summary>
    public class XmlSerializer : ISerializer
    {
        public string ContentType
        {
            get { return MimeTypes.APPLICATION_XML; }
        }

        public object Deserialize(string value, Type type)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
            var encoding = new UTF8Encoding();
            var byteArray = encoding.GetBytes(value);
            using (var memoryStream = new MemoryStream(byteArray))
            {
                return Convert.ChangeType(xmlSerializer.Deserialize(memoryStream), type, CultureInfo.InvariantCulture);
            }
        }

        public string Serialize(object objectToSerialize)
        {
            MemoryStream memoryStream = null;
            try
            {
                var xmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
                memoryStream = new MemoryStream();
                using (var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    xmlSerializer.Serialize(memoryStream, objectToSerialize);
                    memoryStream = xmlTextWriter.BaseStream as MemoryStream;
                    var encoding = new UTF8Encoding();
                    return encoding.GetString(memoryStream.ToArray());
                }
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
            }
        }
    }
}